package com.woniuxy.factory.service.imp;


import com.woniuxy.factory.entity.ResponseResult;
import com.woniuxy.factory.entity.SystemMenu;
import com.woniuxy.factory.exception.MenuException;
import com.woniuxy.factory.mapper.SystemMenuMapper;
import com.woniuxy.factory.service.SystemMenuService;
import com.woniuxy.factory.util.NodeUtil;
import com.woniuxy.factory.util.Settings;
import com.woniuxy.factory.util.TreeUtil;
import com.woniuxy.factory.vo.MenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;

@Service
public class SystemMenuServiceImp implements SystemMenuService {

    @Autowired
    SystemMenuMapper systemMenuMapper;

    @Override
    public Map<String, Object> findMenus() {
        //新建容器
        Map<String, Object> map = new HashMap<>(16);
        Map<String, Object> home = new HashMap<>(16);
        Map<String, Object> logo = new HashMap<>(16);
        List<MenuVO> systemMenuInfo = new ArrayList<>();
        //查询符合条件的菜单项
        List<SystemMenu> systemMenuList = systemMenuMapper.selectMenuListUsed();
        //封装VO
        for (SystemMenu e : systemMenuList) {
            MenuVO menuVO = new MenuVO();
            menuVO.setId(e.getSymId());
            menuVO.setPid(e.getPid());
            menuVO.setHref(e.getHref());
            menuVO.setTitle(e.getTitle());
            menuVO.setIcon(e.getIcon());
            menuVO.setTarget(e.getTarget());
            systemMenuInfo.add(menuVO);
        }
        //建立树结构
        map.put("menuInfo", TreeUtil.toTree(systemMenuInfo, Settings.MENU_TREE_ROOT_ID));
        //加入页面头内容
        home.put("title", "首页");
        home.put("href", "page/welcome-1.html");
        logo.put("title", "后台管理系统");
        //静态资源文件路径,可使用默认的logo.png
        logo.put("image", "images/logo.png");
        map.put("homeInfo", home);
        map.put("logoInfo", logo);
        return map;
    }

    @Override
    public ResponseResult showAllMenu() {
        //初始化容器
        ResponseResult<List<SystemMenu>> result = new ResponseResult();
        //查询所有菜单项并加入返回容器
        result.setData(systemMenuMapper.selectMenuList());
        //查询条目数
        result.setCount(systemMenuMapper.selectMenuCount());
        //设置返回code
        result.setCode(0);
        return result;
    }

    @Override
    public ResponseResult addMenu(SystemMenu menu, String menus) {
        //初始化容器
        ResponseResult result = new ResponseResult();
        menu = menuHandle(menu, menus);
        try {
            if (systemMenuMapper.addMenu(menu) == 0) {
                result.setCode(1);
                result.setMsg("添加失败，请重试");
                return result;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new MenuException("数据库异常，请联系管理员");
        }
        result.setCode(0);
        result.setMsg("添加成功");
        return result;
    }

    private SystemMenu menuHandle(SystemMenu menu, String menus) {
        //判断添加的菜单层级
        String[] lvl = menus.split(",");
        //初始化层级和父节点
        int level = 1, index = Settings.MENU_TREE_ROOT_ID;
        for (int i = 0; i < lvl.length; i++) {
            if (lvl[i].equals("-1")) {
                break;
            }
            //确定层级
            level = i + 2;
            try {
                //确定父节点
                index = Integer.parseInt(lvl[i]);
            } catch (Exception e) {
                throw new MenuException("数据异常，请重试");
            }
        }
        //处理图标
        menu.setIcon("fa " + menu.getIcon());
        //赋值父节点
        menu.setPid(index);
        //赋值层级
        menu.setLevel(level);
        //查询排序sort
        menu.setSort(systemMenuMapper.selectSortByPid(index) + 1);
        //赋值标签
        if (menu.getTarget() == null || menu.getTarget() == "")
            menu.setTarget("_self");
        return menu;
    }

    @Override
    public Map selectParentForAdd(int id) {
        //初始化容器
        Map<String, Object> map = new HashMap();
        //获取所有菜单
        List<SystemMenu> list = systemMenuMapper.selectMenuList();
        if (id == 1) {
            map.put("menuList", list);
            map.put("nodes", null);
            return map;
        }
        //获取层级
        int lv = systemMenuMapper.selectLevelById(id);
        if (lv == 4)
            throw new MenuException("菜单不要超过四层");
        //新建节点数组
        int[] nodes = new int[lv];
//        //获取父节点
//        int parent ;
//        int index = id , i = 1;
//        while ((parent = systemMenuMapper.selectParentById(index))!=0){
//            index = parent;
//            nodes[nodes.length-i] = index;
//            i++;
//        }
        map.put("menuList", list);
        //调用递归寻找父节点
        nodes = NodeUtil.toNodes(list, nodes, id);
        map.put("nodes", nodes);
        return map;
    }

    @Override
    public Map getMenu(int id) {
        //初始化容器
        Map<String, Object> map = new HashMap();
        SystemMenu systemMenu = null;
        //获取所有菜单
        List<SystemMenu> list = systemMenuMapper.selectMenuList();
        for (SystemMenu m : list) {
            if (m.getSymId() == id) {
                systemMenu = m;
                break;
            }
        }
        //非空判定
        if (systemMenu == null)
            throw new MenuException("MENU 404 NOT FOUND");
        map.put("menu", systemMenu);
        if (id == 1) {
            map.put("menuList", list);
            map.put("nodes", null);
            return map;
        }
        //获取父节点
        int pid = systemMenu.getPid();
        //获取层级
        int lv = systemMenuMapper.selectLevelById(pid);
        //节点数组
        int[] nodes = new int[lv];
        map.put("menuList", list);
        if (pid == 1) {
            map.put("menuList", list);
            map.put("nodes", null);
            return map;
        }
        //调用递归寻找父节点
        nodes = NodeUtil.toNodes(list, nodes, pid);
        map.put("nodes", nodes);
        return map;
    }

    @Override
    @Transactional
    public ResponseResult editMenu(SystemMenu menu, String menus) {
        //初始化容器
        ResponseResult result = new ResponseResult();
        SystemMenu menu0;
        try {
            menu0 = systemMenuMapper.selectMenuById(menu.getSymId());
            if(menu0==null)
                throw new RuntimeException("数据有误");
        }catch (Exception e){
            System.out.println(e.getMessage());
            throw new MenuException("数据有误，请重试");
        }
        menu = menuHandle(menu, menus);
        //判断节点是否发生改变
        if(menu0.getPid()==menu.getPid()){
            //节点没发生改变，则层级，序号不变
            menu.setSort(menu0.getSort());
            menu.setLevel(menu0.getLevel());
        }
        //设置修改时间
        menu.setUpdateAt(new Date());
        try {
            if (systemMenuMapper.editMenu(menu) == 0) {
                result.setCode(1);
                result.setMsg("添加失败，请重试");
                return result;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new MenuException("系统维护中");
        }
        result.setCode(0);
        result.setMsg("修改成功");
        return result;
    }

    @Override
    public int upSort(Integer id) {
        int i = 0;
        try {
            //获取元素
            SystemMenu menu0 = systemMenuMapper.selectMenuById(id);
            if (menu0 == null) {
                throw new MenuException("输入参数有误，请重试");
            }
            //获取上一个元素
            SystemMenu menu1 = systemMenuMapper.selectMenuByPidAndSort(menu0.getPid(), menu0.getSort() - 1);
            if (menu1 == null) {
                throw new MenuException("系统维护中");
            }
            //交换序号
            menu0.setSort(menu0.getSort() - 1);
            menu1.setSort(menu1.getSort() + 1);
            //更新数据库
            try {
                i += systemMenuMapper.editMenu(menu0);
                i += systemMenuMapper.editMenu(menu1);
            } catch (Exception e) {
                throw new SQLException("...");
            }
        }catch (SQLException e){
            System.out.println(e.getMessage());
            throw new MenuException("系统维护中。。。");
        }
        return i;
    }

    @Override
    public int selectEndSort(Integer pid) {
        return systemMenuMapper.selectSortByPid(pid);
    }

    @Override
    public int downSort(Integer id) {
        int i = 0;
        try {
            //获取元素
            SystemMenu menu0 = systemMenuMapper.selectMenuById(id);
            if (menu0 == null) {
                throw new MenuException("输入参数有误，请重试");
            }
            //获取下一个元素
            SystemMenu menu1 = systemMenuMapper.selectMenuByPidAndSort(menu0.getPid(), menu0.getSort() + 1);
            if (menu1 == null) {
                throw new MenuException("系统维护中");
            }
            //交换序号
            menu0.setSort(menu0.getSort() + 1);
            menu1.setSort(menu1.getSort() - 1);
            //更新数据库
            try {
                i += systemMenuMapper.editMenu(menu0);
                i += systemMenuMapper.editMenu(menu1);
            } catch (Exception e) {
                throw new SQLException("...");
            }
        }catch (SQLException e){
            System.out.println(e.getMessage());
            throw new MenuException("系统维护中。。。");
        }
        return i;
    }


}